package com.jy.admin.rest;

import com.alibaba.fastjson.JSONObject;
import com.fqgj.common.utils.MD5;
import com.fqgj.common.utils.StringUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jsoniter.JsonIterator;
import com.jsoniter.any.Any;
import com.jsoniter.output.JsonStream;
import com.jy.admin.annotations.AdminSignIgnore;
import com.jy.admin.auth.anno.VisitorAccessible;
import com.jy.admin.db.dao.*;
import com.jy.admin.db.entity.*;
import com.jy.admin.services.cashPocket.*;
import com.jy.admin.services.cashPocket.vo.ImagesVo;
import com.jy.bo.common.conf.api.ApiResponse;
import com.jy.bo.common.conf.util.HttpUtil;
import kong.unirest.HttpResponse;
import kong.unirest.Unirest;
import okhttp3.*;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

import static com.jy.admin.services.cashPocket.LittleOrangeService.execCurl;
import static com.jy.bo.common.conf.util.HttpUtil.createIgnoreVerifySSL;
import static com.jy.bo.common.conf.util.HttpUtil.getIgnoreSslHostnameVerifier;
import static com.qianli.cashmama.pay.common.util.HeaUtil.sha1;


/**
 * Created with IntelliJ IDEA.
 * User: binary (mr.vencnet@gmail.com)
 * Date: 2020-06-02
 * Time: 17:18
 */
@RestController
@RequestMapping("/test1")
public class TestCredexController {

    private static final Logger LOGGER = LoggerFactory.getLogger(TestCredexController.class);

    @Autowired
    private CeAgentAccountDao agentAccountDao;

    @Autowired
    private CeOrdersDetailDao ordersDetailDao;

    @Autowired
    private CeOrdersDao ordersDao;

    @Autowired
    private CeCommentPushLogDao ceCommentPushLogDao;

    @Autowired
    private OkRupeeService okRupeeService;

    @Autowired
    private ChenXingNewService lingLoanService;

    @AdminSignIgnore
    @RequestMapping("/hasLogin")
    @VisitorAccessible
    public String ok12345() {
        CeAgentAccountEntity infinitycash01 = agentAccountDao.getByAgentCode("okrupee107");
        okRupeeService.hasLogin(infinitycash01);
        return "ok";
    }

    @AdminSignIgnore
    @RequestMapping("/updateList")
    @VisitorAccessible
    public String ok1234() {
        CeAgentAccountEntity richloan01 = agentAccountDao.getByAgentCode("BZT101");
        lingLoanService.updateOrderList(richloan01);
        return "ok";
    }

    @AdminSignIgnore
    @RequestMapping("/updateDetail")
    @VisitorAccessible
    public String ok2123() {
        CeAgentAccountEntity infinitycash01 = agentAccountDao.getByAgentCode("BZT101");
        lingLoanService.updateOrderDetailInfo(infinitycash01);
        return "ok";
    }

    @AdminSignIgnore
    @RequestMapping("/compost")
    @VisitorAccessible
    public String ok3123() {
        CeAgentAccountEntity rupeego01 = agentAccountDao.getByAgentCode("BZT101");
        lingLoanService.compostCollectionData(rupeego01);
        return "ok";
    }

    @AdminSignIgnore
    @RequestMapping("/push")
    @VisitorAccessible
    public String ok4123() {
        CeAgentAccountEntity rupeego01 = agentAccountDao.getByAgentCode("BZT101");
        lingLoanService.pushDataToCollection(rupeego01);
        return "ok";
    }

    @AdminSignIgnore
    @RequestMapping("/check")
    @VisitorAccessible
    public String okcheck() {
        CeAgentAccountEntity rupeego01 = agentAccountDao.getByAgentCode("BZT101");
        lingLoanService.checkOrdersPaidStatus(rupeego01);
        return "ok";
    }

    @AdminSignIgnore
    @RequestMapping("/updateCheck")
    @VisitorAccessible
    public String okupdatecheck() {
        CeAgentAccountEntity rupeego01 = agentAccountDao.getByAgentCode("fiWallet01");
        lingLoanService.updatePaidOrderToCollection(rupeego01);
        return "ok";
    }

    @AdminSignIgnore
    @RequestMapping("/send")
    @VisitorAccessible
    public String oksend() {
        List<CeCommentPushLogEntity> listByStatus = ceCommentPushLogDao.getListByStatus(1);
        lingLoanService.sendNote(listByStatus.get(0));
        return "ok";
    }

    @AdminSignIgnore
    @RequestMapping("/refreshOrderList")
    @VisitorAccessible
    public String refreshOrderList() {
        CeAgentAccountEntity rupeego01 = agentAccountDao.getByAgentCode("okmoney03");
        lingLoanService.updateOrderList(rupeego01);
        return "ok";
    }

    @AdminSignIgnore
    @RequestMapping("/repayLink")
    @VisitorAccessible
    public String okLink() {
        String link = lingLoanService.updateRepaymentLink("306408449422400901", false);
        return link;
    }

    @AdminSignIgnore
    @RequestMapping("/extension/repayLink")
    @VisitorAccessible
    public String okExtensionLink() {
        String link = lingLoanService.updateExtensionRepaymentLink("306408449422400901", false);
        return link;
    }

    @AdminSignIgnore
    @RequestMapping("/repairDetails")
    @VisitorAccessible
    public String okRepair() {
        List<CeAgentAccountEntity> rupeego = agentAccountDao.getAccountsMerchantCode("rocketscash");
        for (int i = 0; i < rupeego.size(); i++) {
            List<CeOrdersEntity> todayListByAgent = ordersDao.getTodayListByAgent(rupeego.get(i).getAgentCode());
            for (int j = 0; j < todayListByAgent.size(); j++) {
                CeOrdersDetailEntity byKeyAndMerchantAndOrderNo = ordersDetailDao.getByKeyAndMerchantAndOrderNo(todayListByAgent.get(j).getMerchantCode(), "fileList", todayListByAgent.get(j).getOrderNo());
                if (byKeyAndMerchantAndOrderNo == null) {
                    LOGGER.error("=== 查询详情失败 ====,orderNo:{}", todayListByAgent.get(j).getOrderNo());
                    continue;
                }
                CeOrdersDetailEntity imagesOrder = ordersDetailDao.getByKeyAndMerchantAndOrderNo(todayListByAgent.get(j).getMerchantCode(), "images", todayListByAgent.get(j).getOrderNo());
                if (imagesOrder == null) {
                    LOGGER.error("=== 开始 ====");
                    Any orderDetail = JsonIterator.deserialize(byKeyAndMerchantAndOrderNo.getDetailInfo());
                    ImagesVo imagesVo = new ImagesVo();
                    LOGGER.error("=== 开始aadhaarFrontImage ====");

                    imagesVo.setAadhaarFrontImage(orderDetail.get("aadhaarFrontImage").asList().get(0).get("imgUrl").toString());
                    LOGGER.error("=== 开始aadhaarBackImage ====");

                    imagesVo.setAadhaarBackImage(orderDetail.get("aadhaarBackImage").asList().get(0).get("imgUrl").toString());
                    LOGGER.error("=== 开始aadhaarHandheldImage ====");

                    imagesVo.setSelfieImage(orderDetail.get("aadhaarHandheldImage").asList().get(0).get("imgUrl").toString());
                    LOGGER.error("=== 开始setDetailInfo ====");

                    byKeyAndMerchantAndOrderNo.setDetailInfo(JsonStream.serialize(imagesVo));
                    LOGGER.error("=== 开始setDataKey ====");

                    byKeyAndMerchantAndOrderNo.setDataKey("images");
                    LOGGER.error("=== 开始插入 ====");

                    ordersDetailDao.insert(byKeyAndMerchantAndOrderNo);
                    LOGGER.error("=== 插入结束 ====");

                    List<String> list = Lists.newArrayList();
                    list.add(orderDetail.get("aadhaarFrontImage").asList().get(0).get("imgUrl").toString());
                    list.add(orderDetail.get("aadhaarBackImage").asList().get(0).get("imgUrl").toString());
                    list.add(orderDetail.get("aadhaarHandheldImage").asList().get(0).get("imgUrl").toString());

                    byKeyAndMerchantAndOrderNo.setDetailInfo(JsonStream.serialize(list));
                    LOGGER.error("=== 开始setDataKey ====");

                    byKeyAndMerchantAndOrderNo.setDataKey("images2");
                    LOGGER.error("=== 开始插入 ====");

                    ordersDetailDao.insert(byKeyAndMerchantAndOrderNo);
                }
            }
        }
        return "ok";
    }

    @AdminSignIgnore
    @RequestMapping("/list")
    @VisitorAccessible
    public String okList() {
        try {
            Unirest.config().httpClient(HttpClients.custom().setSSLContext(createIgnoreVerifySSL())
                    .setSSLHostnameVerifier(getIgnoreSslHostnameVerifier()).build());
            HttpResponse<String> response = Unirest.post("https://client.cooindfodghr.com/api/cm_dunning_case/page")
                    .header("Content-Type", "application/json")
                    .header("auth", "134E9387179449A88A7ACD25FD6D75FE-86400")
                    .header("Referer", "https://client.cooindfodghr.com/all-cm-dunning-case-list")
                    .header("lang", "en-us")
                    .header("customer", "3XELTZUO")
                    .body("{\"query\":{\"pageNo\":1,\"pageSize\":20,\"orderQuery\":{\"userInfo\":{}},\"status\":\"PENDING\",\"filterAllCase\":true}}")
                    .asString();
            return response.getBody();
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            e.printStackTrace();
        }
        return "";
    }

    private final static String Key = "sATU62685bhpegE-E761gPeN-dq6y89QW-7TJr5PVB-2F1H36tLYfW6TL5";

    public Map<String, String> getHeaders(CeAgentAccountEntity agentAccount) {
        String requestHeader = agentAccount.getRequestHeader();
        Map headers = Maps.newHashMap();
        if (StringUtils.isNotEmpty(requestHeader)) {
            Map<String, Any> stringAnyMap = JsonIterator.deserialize(requestHeader).asMap();
            stringAnyMap.keySet().forEach(k -> {
                headers.put(k, stringAnyMap.get(k).toString());
            });
        }

        return headers;
    }

    @RequestMapping("/account/get")
    public ApiResponse getWAAccount(String agentCode, String orderNo) {

        CeAgentAccountEntity agentAccount = agentAccountDao.getByAgentCode(agentCode);
        CeOrdersEntity ordersEntity = ordersDao.getTodayOneByOrderNoAndAgentCode(orderNo, agentCode);
        Any orderInfo = JsonIterator.deserialize(ordersEntity.getOrderInfo());
        Map<String, String> headers = getHeaders(agentAccount);
        String cmOrderId = orderInfo.get("cmOrderId").toString();
        com.alibaba.fastjson.JSONObject params = new JSONObject();
        params.put("id", cmOrderId);
        long st = System.currentTimeMillis();
        String stt = MD5.md5("#cG8wbGttMW5ibG16eDZoYQ#3XELTZUO#" + st);
        String repaymentInfoUrl = "https://client.eivxmsffjgbin.com/api/cm_order/one";
        String[] repaymentCmds = {"curl", "--location",
                "--request", "POST", repaymentInfoUrl,
                "--header", "Content-Type: application/json",
                "--header", "lang: en-us",
                "--header", "customer: 3XELTZUO",
                "--header", "auth:" + headers.get("auth"),
                "--header", "Referer: " + "https://client.eivxmsffjgbin.com/cm-dunning-case-list",
                "--header", "accept: application/json",
                "--header", "accept-encoding: gzip, deflate, br",
                "--header", "accept-language: zh-CN,zh;q=0.9",
                "--header", "content-type: application/json; charset=utf-8",
                "--header", "st:" + st,
                "--header", "stt:" + stt,
                "--header", "origin: https://client.eivxmsffjgbin.com",
                "--header", "\"Chromium\";v=\"104\", \" Not A;Brand\";v=\"99\", \"Google Chrome\";v=\"104\"",
                "--header", "sec-ch-ua-mobile: ?0",
                "--header", "sec-ch-ua-platform: \"macOS\"",
                "--header", "sec-fetch-dest: empty",
                "--header", "sec-fetch-mode: cors",
                "--header", "sec-fetch-site: same-origin",
                "--header", "user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36",
                "--data-raw", params.toString()};
        String repaymentInfoResult = execCurl(repaymentCmds);
        return new ApiResponse(repaymentInfoResult);
    }


    public static void main(String[] args) {
        try {
            // 重置随机数种子。
            Random rand = new Random();
            int randomNum = rand.nextInt(900000000) + 100000000;  //生成9位随机数

            String appSecret = "jIw19Pwnx1b1"; // 请替换为您从开发者平台获取的 App Secret。

            Long timestamp = System.currentTimeMillis(); // 获取时间戳（毫秒）。

            String signature = null;
            signature = sha1(appSecret + randomNum + timestamp);


            LOGGER.info("~~~", randomNum + "---" + timestamp + "---" + signature);

            OkHttpClient client = new OkHttpClient().newBuilder()
                    .build();
            MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
            RequestBody body = RequestBody.create(mediaType, "fromUserId=1713770534616006656&toUserId=1689916233351172096&objectName=RC:InfoNtf&content={\"message\":\"HelloKitty\",\"extra\":\"\"}&verifyBlacklist=0&isPersisted=1&isIncludeSender=0&disablePush=0");
            Request request = new Request.Builder()
                    .url("https://api.us-light-api.com/message/private/publish.json")
                    .method("POST", body)
                    .addHeader("Host", "api.us-light-api.com")
                    .addHeader("App-Key", "sfci50a7sm0pi")
                    .addHeader("Nonce", String.valueOf(randomNum))
                    .addHeader("Timestamp", String.valueOf(timestamp))
                    .addHeader("Signature", signature)
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .build();
            Response response = client.newCall(request).execute();
        } catch (IOException | NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public static String hashWithSHA1(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            byte[] hash = md.digest(input.getBytes(StandardCharsets.UTF_8));
            return bytesToHex(hash);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    private static String bytesToHex(byte[] hash) {
        StringBuilder hexString = new StringBuilder(2 * hash.length);
        for (int i = 0; i < hash.length; i++) {
            String hex = Integer.toHexString(0xff & hash[i]);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }

}



